<template>
    <div style="color: white;">
        <button @click="prevDay"><a-icon type="left" /></button>
        <span>{{ formattedDate }} &nbsp;</span>
        <button @click="nextDay"><a-icon type="right" /></button>
    </div>
</template>

<script>
export default {
    name: 'DateTimeWidget',
    props: {
        value: {
            type: Date,
            required: true
        }
    },
    data() {
        return {
            currentDate: this.value || new Date(new Date().setDate(new Date().getDate() - 1)), // 默认昨天的日期
            timeoutId: null,
        };
    },
    computed: {
        formattedDate() {
            const year = this.currentDate.getFullYear();
            const month = String(this.currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始所以需要加1
            const day = String(this.currentDate.getDate()).padStart(2, '0');
            return `${year}年${month}月${day}日`;
        },
    },
    watch: {
        value(newValue) {
            this.currentDate = newValue;
        },
        currentDate(newValue) {
            this.$emit('input', newValue);
            this.$emit('change', newValue); // 触发 change 事件
        }
    },
    methods: {
        prevDay() {
            const newDate = new Date(this.currentDate);
            newDate.setDate(newDate.getDate() - 1);
            this.currentDate = newDate;
        },
        nextDay() {
            const newDate = new Date(this.currentDate);
            newDate.setDate(newDate.getDate() + 1);
            this.currentDate = newDate;
        },
        scheduleNextMidnightUpdate() {
            const now = new Date();
            const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
            const timeUntilMidnight = midnight.getTime() - now.getTime();

            this.timeoutId = setTimeout(() => {
                this.updateTime();
                this.scheduleNextMidnightUpdate(); // 递归调用以持续调度
            }, timeUntilMidnight);
        },
        updateTime() {
            this.currentDate = new Date(); // 更新为当前日期
        }
    },
    mounted() {
        this.scheduleNextMidnightUpdate(); // 在挂载时启动定时器
    },
    beforeDestroy() {
        // 清除定时器以防止内存泄漏
        clearTimeout(this.timeoutId);
    }
};
</script>

<style scoped>
/* 添加一些样式以美化按钮 */
button {
    background-color: transparent;
    border: none;
    color: white;
    font-size: 16px;
    cursor: pointer;
    margin: 0 5px;
}

button:hover {
    text-decoration: underline;
}
</style>



